package org.bbs.demo.user.api;

import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.advice.SysException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.user.dao.UserSignupDao;
import org.bbs.demo.user.dto.UserSignupDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class UserSignupApi {

    @Autowired
    private UserSignupDao userSignupDao;

    @PostMapping("/signup")
    public Result Signup(@Validated @RequestBody UserSignupDto signupDto){

        // 检查邮箱格式
        if (!signupDto.getMail().contains("@")){
            throw new BusinessException("无效的邮箱");
        }

        // 检查邮箱是否注册
        if (userSignupDao.findUserByEmail(signupDto) > 0) {
            throw new BusinessException("邮箱已注册");
//            return Result.err(BBSConstants.CODE_ERR_BUSINESS, "邮箱已注册");
        }

        // 生成新用户账号
        String userId = userSignupDao.findMaxUid();
        if (userId == null){
            userId = "10000000";
        }
        userId = String.format("%08d", Integer.parseInt(userId)+1);  //0 代表前面补充0     8 代表长度为8
        signupDto.setUser_id(userId);

        // 插入新用户记录
        try {
            userSignupDao.userSignup(signupDto);
        }
        catch (Exception err){
            throw new SysException("数据库插入失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "数据库插入用户信息失败");
        }

        return Result.OK("注册成功", userId);
    }
}
